FileUpload = function(formId) {
    this.idkey          = 'APC_UPLOAD_PROGRESS';    
    this.id             = null;
    this.form           = null;
    this.timerId        = null;
    this.interval       = 1000; // 1 second
    this.allowable      = true;
    this.retry          = 0;
    this.retryLimit     = 3;
    this.uploadFinished = false;
    this.infoUpdated    = false;
    this.isDone         = false;

    this.init = function() {
        if($("#myfile").val() == "")
        {
            alert("Bạn phải chọn một file!");
            return false;
        }

        this.form = $("#"+formId);
        var fileName = $("#myfile").val();
		while (fileName.indexOf("\\") != -1) fileName = fileName.slice(fileName.indexOf("\\") + 1);
		var title = fileName.substr(0, fileName.lastIndexOf("."));
		title = jQuery.trim(title.replace(/([\-_\.\s])+/g, ' '));

		$('#title').val(title);

        this.submitForm();
    }
    
    this.getStatus = function() {
        var $this = this;
        if($this.allowable) {
            $this.allowable = false;
            $.ajax({
                type: "post",
                url: "/upload/get_status",
                data: "upload_id=" + $("#upload_id").val(),
                cache: false,
                dataType: "json",
                error: function() {
                    $this.retry++;
                    if($this.retry > $this.retryLimit) {
                        $this.uploadFail();
                    }
                },
                success: function(result) {
                    var data = result.data;
                    var typeInfo = result.typeInfo;

                    if (!typeInfo) {
                        $this.displayError('Nội dung file không hợp lệ!');
                        $this.cleanUp();
                        return false;
                    }

                    if(result.error) {
                        $this.displayError(result.msg);
                        $this.cleanUp();
                        return false;
                    }

                    $this.uploadFinished    = Boolean(data.finished);
                    total                   = data.total;
                    complete                = data.complete;
                    percent                 = data.percent;
                    speed                   = data.speed;
                    duration                = data.duration;
                    remaining               = data.remaining;

                    $("#progress-bar").css("width", percent+"%");
                    $("#progress-percent").text(percent+"%");
                    $("#upload_status").text("\u0110ang tải lên");
                    $("#upload_speed").text(speed + " kbps");
                    $("#upload_duration").text(duration);
                    $("#upload_remaining").text(remaining);

                    $this.allowable = true;

                    if($this.uploadFinished) {
                        $("#upload_status").html("<font color=\"red\">Hoàn thành</font>");
                        $this.cleanUp();
                        
                        if($this.infoUpdated) $this.finish();
                    }

                    return false;
                }
            });
        }
    }

    this.finish = function() {
        var $this = this;
        if(!$this.isDone) {
            $.ajax({
                type: "post",
                url: "/upload/finish",
                data: "upload_id=" + $("#upload_id").val(),
                cache: false,
                dataType: "json",
                error: function() {
                    $this.uploadFail();
                },
                success: function(result) {
                    $("#video_size").html(result.width + 'x' + result.height);
                    $("#video_bitrate").html(result.bitrate);
                    if(result.error) {
                        $("#video_status").html("<font color=\"red\">Video không đạt yêu cầu!</font>")
                    }
                    $this.displaySummary();
                }
            });
            
            $this.isDone = true;
        }
    }

    this.updateInfo = function(noMsg) {
        var $this = this;
        var cb = function (res) {
            mask.remove();

            if(!noMsg)
            {
                if(res.msg != "")
                {
                    if(res.error == 0)
                    {
                        $this.updateSuccess(res.msg);
                        $this.infoUpdated = true;

                        if($this.uploadFinished) $this.finish();
                    }
                    else {
                        $this.infoUpdated = false;
                        $this.updateError(res.msg);
                    }
                }

                $("#title").setError(res.emsg.title);
                $("#description").setError(res.emsg.description);
                $("#tag").setError(res.emsg.tag);
                $("#price").setError(res.emsg.price);
                $("#download-price").setError(res.emsg.download_price);
                $("#category_id").setError(res.emsg.category_id);
            }
        };

        source = $('input[name=source]:checked').val();
        source = source == undefined ? 'vn' : source;
        var description_var = $('#description').htmlarea('toHtmlString');
        var clipData = {
            'upload_id'     : $("#upload_id").val(),
            'title'			: $('#title').val(),
            //'description'	: $('#description').val(),
            'description'	: description_var,
            'tag'           : $('#tag').val(),
            'price'         : $('#price').val(),
            'download_price': $('#download-price').val(),
            'category_id'	: $('#category_id').val(),
            'subcp_id'      : $('#subcp_id').val(),
            'source'        : source,
            'hd'            : $('#hd').is(":checked") ? 1 : 0
        };

        mask = $("#upload-info").showMaskLayer();

        try
        {
            $.ajax({
                type: "post",
                url: "/upload/update_info",
                data: clipData,
                dataType: "json",
                success: cb
            });
        } catch(ex) {}
    }

    this.submitForm = function() {
        document.frmUploadVideo.submit();
        var $this = this;
        $this.displayInfo();

        $.ajax({
            type: "post",
            url: "/upload/validate",
            data: "upload_id=" + $("#upload_id").val() + "&member_id=" + $("#member_id").val(),
            cache: false,
            dataType: "json",
            error: function() {
                $this.uploadFail();
            },
            success: function(result) {
                if(result.error == 1) {
                    $this.displayError(result.msg);
                    $this.cleanUp();
                    return false;
                }
                else $this.timerId = setInterval("getStatus()", $this.interval);
            }
        });
    }

    this.updateSuccess = function(msg) {
        if(msg) {
            $('#msg-report').removeClass('msg2').addClass('msg').text(msg);
        }
    }

    this.updateError = function(msg) {
        if(msg) {
            $('#msg-report').removeClass('msg').addClass('msg2').text(msg);
        }
    }
    
    this.getStatusError = function() {

    }

    this.updateProgress = function() {
        
    }

    this.cleanUp = function() {
        window.clearInterval(this.timerId);
    }

    this.uploadFail = function() {
        this.displayError('Có lỗi xảy ra! <a href="/video/upload">Upload lại</a>');
        this.cleanUp();
    }

    this.displayInfo = function() {
        $('#upload-form').hide();
        $('#upload-progress').show();
        $('#upload-info').show();
        $("#description").htmlarea("dispose");
        $("#description").htmlarea();
    }

    this.displayError = function(msg) {
        $('#upload-info').hide();
        $('#upload-report').show().html(msg);
    }

    this.displaySummary = function() {
        $('#upload-progress').hide();
        $('#upload-info').hide();
        $('#upload-summary').show();
    }
}

getStatus = function() {
    fileUploader.getStatus();
}

cleanUp = function() {
    fileUploader.cleanUp();
}

jQuery.fn.setError = function(message) {
    var $this = $(this).next();
    if(message != undefined && message != "") {
        $this.text(message);
    } else {
        $this.text("");
    }
};

var fileUploader = new FileUpload('frmUploadVideo');